//
//  VIPView.swift
//  ShouChong
//
//  Created by yw on 2024/9/23.
//

import SwiftUI
import RevenueCat
import ProgressHUD

struct VIPView: View {
    @Environment(\.presentationMode) var isShow
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    private struct VipModel:Identifiable {
        var id:String = UUID().uuidString
        var price:String
        var title:String
        var subTitle:String
        var package:Package
    }
    @State private var list:[VipModel] = []
    @State private var currentId:String = ""
    /// 是否订阅
    @State private var isPruchase:Bool = false
    @State private var expirationString:String = ""
    @State private var startString:String = ""
    @ObservedObject var userVM:UserViewModel = UserViewModel(getNow: false)
    var body: some View {
        NavigationView{
            ScrollView{
                VStack{
                    HeaderView
                        .padding(10)
                    if !isPruchase {
                        PriceView
                            .padding(20)
                        Text("定期发送账单，可随时取消")
                            .foregroundColor(Color("color_gray"))
                            .font(Font.system(size: 14, weight: .medium, design: .rounded))
                    }
                    
                    HStack {
                        TitleList
                        Spacer()
                    }.padding(20)
                    if !isPruchase {
                        PurchaseBtn
                    } else {
                        HStack{
                            PurchaseDateView
                            Spacer()
                        }.padding(20)
                    }
                    HStack {
                        PrivacyView
                       
                    }.padding(20)
                    
                }
            }
            
            .navigationBarItems(
                leading: Image(systemName: "xmark")
                    .foregroundColor(Color("color_text_black"))
                    .onTapGesture {
                        shake()
                        dismissClick()
                    }
            )
            .navigationBarItems(
                trailing: Text("恢复订阅")
                    .foregroundColor(Color("color_text_black"))
                    .onTapGesture {
                        shake()
                        recoverBuy()
                    }
            )
        }
        
        .onAppear{
            checkPurchaseInfo()
        }
        
    }
    
    private func shake() {
        let generator = UIImpactFeedbackGenerator(style: .light)
        generator.prepare()
        generator.impactOccurred()
    }
    
    private func date2String(_ date:Date, dateFormat:String = "yyyy-MM-dd HH:mm") -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let date = formatter.string(from: date)
        return date
    }
    
    ///订阅后开始、结束时间展示View
    private var PurchaseDateView:some View {
        VStack {
            HStack {
                Text("开始订阅时间:")
                Text(startString)
            }.padding(.bottom,10)
            HStack {
                Text("结束订阅时间:")
                Text(expirationString)
            }
        }.foregroundColor(Color("color_text_black"))
            .font(Font.system(size: 14))
    }
    
    ///订阅按钮
    private var PurchaseBtn:some View {
        Button {
            buy()
        } label: {
            Text("开始订阅")
                .frame(height: 50)
                .frame(width:kScreenWidth - 60)
                .font(Font.system(size: 16, weight: .bold, design: .rounded))
                .foregroundColor(Color("color_white"))
                .padding(.horizontal,20)
                .background(Color(currentMainColor))
                .cornerRadius(10)
            
        }
        .offset(x: 0, y: 20)
    }
    
    
    ///隐私相关
    private var PrivacyView:some View {
        VStack {
            HStack{
                Text("您可以查看")
                
                Text("EULA")
                    .underline(true,color: Color("color_gray"))
                    .onTapGesture {
                        tapEULA()
                    }
                Text("隐私协议")
                    .underline(true,color: Color("color_gray"))
                    .onTapGesture {
                        tapPrivate()
                    }
                Spacer()
            }
            HStack{
                Text("或者反馈")
                Text("支付问题")
                    .underline(true,color: Color("color_gray"))
                    .onTapGesture {
                        tapProblem()
                    }
                Spacer()
            }
        }
       
        .font(Font.system(size: 14))
        .foregroundColor(Color("color_gray"))
    }
    
    /// VIP功能展示list
    private var TitleList:some View {
        VStack(alignment:.leading) {
            Text("❎不展示广告")
//                .underline(true, color: Color(currentMainColor))
                .font(Font.system(size: 18, weight: .bold, design: .rounded))
                .foregroundColor(Color(currentMainColor))
            Text("🌈会员专属主题颜色")
//                .underline(true, color: Color(currentMainColor))
                .font(Font.system(size: 18, weight: .bold, design: .rounded))
                .foregroundColor(Color(currentMainColor))
                .padding(.vertical,10)
            Text("👑展示会员专属logo")
//                .underline(true, color: Color(currentMainColor))
                .font(Font.system(size: 18, weight: .bold, design: .rounded))
                .foregroundColor(Color(currentMainColor))
                .padding(.bottom,10)
        }
    }
    
    /// 价格表
    private var PriceView:some View {
        HStack{
            ForEach(list) { item in
                VStack{
                    Text(item.title)
                        .frame(maxWidth:.infinity)
                        .lineLimit(2)
                        .minimumScaleFactor(0.8)
                        .foregroundColor(currentId == item.id ? Color("color_text_white"):Color("color_text_black"))
                        .font(Font.system(size: 16, weight: .bold, design: .rounded))
                    
                    Text(item.price)
                        .frame(maxWidth:.infinity)
                        .lineLimit(2)
                        .minimumScaleFactor(0.8)
                        .foregroundColor(currentId == item.id ? Color("color_text_white"):Color("color_text_black"))
                        .padding(.vertical,10)
                        .font(Font.system(size: 20, weight: .bold, design: .rounded))
                    Text(item.subTitle)
                        .frame(maxWidth:.infinity)
                        .lineLimit(2)
                        .minimumScaleFactor(0.8)
                        .foregroundColor(currentId == item.id ? Color("color_text_white"):Color("color_text_black"))
                        .font(Font.system(size: 13, weight: .medium, design: .rounded))
                        .frame(height:44)
                }
                .padding(.horizontal,20)
                .padding(.vertical,10)
                .background(currentId == item.id ? Color(currentMainColor) : Color("color_bg"))
                .cornerRadius(10)
                .onTapGesture {
                    shake()
                    currentId = item.id
                }
            }
        }
    }
    
    
    /// 顶部标题栏
    private var HeaderView:some View {
        VStack(alignment:.leading){
            HStack {
                Text("撸了么App")
                    .font(Font.system(size: 20, weight: .heavy, design: .rounded))
                    .foregroundColor(Color("color_text_black"))
                Text("VIP")
                    .font(Font.system(size: 18, weight: .heavy, design: .rounded))
                    .foregroundColor(Color("color_text_white"))
                    .padding(.horizontal,10)
                    .padding(.vertical,4)
                    .background(Color(currentMainColor))
                    .cornerRadius(10)
            }
            RoundedRectangle(cornerRadius: 2)
                .fill(Color(currentMainColor))
                .frame(maxWidth: .infinity)
                .frame(height: 4)
                .padding(.vertical,10)
            
            Text(isPruchase ? "恭喜您，您已解锁以下功能" : "解锁VIP,体验更多功能")
                .font(Font.system(size: 18, weight: .bold, design: .rounded))
                .foregroundColor(Color("color_text_black"))
            
        }
    }
    
    private func dismissClick() {
        isShow.wrappedValue.dismiss()
    }
    
    /// 发起订阅
    private func buy() {
        shake()
        if currentId.count != 0 {
            let currentItem = list.filter { item in
                return item.id == currentId
            }
            ProgressHUD.animate("加载中")
            Purchases.shared.purchase(package: currentItem.first!.package) { (transaction, customerInfo, error, userCancelled) in
                ProgressHUD.dismiss()
                if customerInfo?.entitlements[kPurchaseName]?.isActive == true {
                    // Unlock that great "pro" content
                    self.checkPurchaseInfo()
                } else {
                    YWToast.show(text: "支付失败")
                    
                }
            }
            
        } else {
            YWToast.show(text: "获取订阅列表失败")
        }
        
    }
    
    /// 反馈支付问题
    private func tapProblem() {
        let str = "https://docs.qq.com/form/page/DRHloUFljaEt1ckRI?create_type=2&from_page=doc_list_new_form&templateId=gkebcsg94fysdrbb535b6ac1do&u=2bdf7f3b911f455983d0a8cc05dcd68c#/fill"
        if let url = URL(string: str) {
            UIApplication.shared.open(url)
        } else {
            YWToast.show(text: "获取网址失败")
        }
    }
    
    /// 隐私协议
    private func tapPrivate() {
        let str = "https://docs.qq.com/doc/DQWdHV2V2ZnVvSVlj"
        if let url = URL(string: str) {
            UIApplication.shared.open(url)
        } else {
            YWToast.show(text: "获取网址失败")
        }
    }
    
    /// eula
    private func tapEULA() {
        let str = "https://www.apple.com/legal/internet-services/itunes/dev/stdeula"
        if let url = URL(string: str) {
            UIApplication.shared.open(url)
        } else {
            YWToast.show(text: "获取网址失败")
        }
    }
    
    /// 检测订阅状态
    private func checkPurchaseInfo() {
        ProgressHUD.animate("加载中")
        Purchases.shared.getCustomerInfo { customInfo, err in
            ProgressHUD.dismiss()
            guard let customInfo = customInfo, err == nil else {
                YWToast.show(text: "抱歉，未找到可用的订阅套餐")
                self.userVM.setUserInfoVIP(isVIp: false)
                return
            }
            if customInfo.entitlements[kPurchaseName]?.isActive == true {
                print("已经订阅了")
                UserDefaults.standard.set(true, forKey: kVipKey)
                self.isPruchase = true
                self.userVM.setUserInfoVIP(isVIp: true)
                if let expirationDate = customInfo.expirationDate(forProductIdentifier: customInfo.activeSubscriptions.first!),
                   let startDate = customInfo.purchaseDate(forProductIdentifier: customInfo.activeSubscriptions.first!){
                    expirationString = date2String(expirationDate)
                    startString = date2String(startDate)
                }
                
            } else {
                print("没有订阅")
                self.isPruchase = false
                UserDefaults.standard.set(false, forKey: kVipKey)
                self.userVM.setUserInfoVIP(isVIp: false)
                self.fetchSubscriptionPrices()
            }
            
        }
    }
    
    //恢复购买
    private func recoverBuy() {
        print("恢复购买")
        ProgressHUD.animate("正在检测恢复中...")
        Purchases.shared.restorePurchases { customerInfo, error in
            //... check customerInfo to see if entitlement is now active
            ProgressHUD.dismiss()
            if customerInfo?.entitlements[kPurchaseName]?.isActive == true {
                // Unlock that great "pro" content
                self.checkPurchaseInfo()
            } else {
                YWToast.show(text: "抱歉，未找到可以恢复的计划")
            }
        }
    }
    
    // 检索订阅价格
    private func fetchSubscriptionPrices() {
        ProgressHUD.animate("加载中...")
        Purchases.shared.getOfferings { (offerings, error) in
            if let packages = offerings?.current?.availablePackages {
                print(packages)
                ProgressHUD.dismiss()
                // 使用价格更新UI
                packages.indices.forEach { index in
                    let model = VipModel(
                        price: packages[index].localizedPriceString,
                        title: packages[index].storeProduct.localizedTitle,
                        subTitle: packages[index].storeProduct.localizedDescription, package: packages[index])
                    list.append(model)
                }
                currentId = list.first?.id ?? ""
            } else {
                // 未找到可用的套餐
                YWToast.show(text: "抱歉，未找到可用的订阅套餐")
            }
        }
    }
}

